package user

import (
	"api-go/model"
	"api-go/serializer"
	migu "api-go/service/v1/migu"
	"api-go/util"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
)

// 歌曲所需信息
type Song struct {
	Ids      string `form:"id"`
	Platform string `form:"platform"`
	Hash     string `form:"hash"`
}

func (service *Song) SongFlac(uid uint) *serializer.Response {
	//首先判断今天是否签到，未签到无法使用
	//将用户Id转为string类型
	uidString := strconv.FormatUint(uint64(uid), 10)

	//根据Id判断今天是否已经打卡
	dateToday := time.Now().Format("2006-01-02")
	singIn := model.IsDakaByUserId(uidString, dateToday)

	if !singIn {
		return serializer.ErrorResponse(serializer.CodeIsNotDakaToday)
	}

	if service.Platform == "wyy" {
		client := &http.Client{}
		data := url.Values{}

		urlStr := "http://music.fy6b.com/index/mp3orflac"
		data.Set("type", "netease")
		data.Set("id", service.Ids)
		data.Set("option", "flac")

		r, _ := http.NewRequest("POST", urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
		r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
		r.Header.Add("X-Forwarded-For", util.RandIp())
		resp, err := client.Do(r)
		if err != nil {
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}
		defer resp.Body.Close()
		datas, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}
		// fmt.Println(string(data))
		//赋值用于后面将string转为json
		bodyMapData := map[string]interface{}{}
		err = json.Unmarshal(datas, &bodyMapData)
		if err != nil {
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}

		out := map[string]interface{}{}

		urlStr = "https://music.163.com/api/v3/song/detail?c=[{id:" + service.Ids + "}]"

		ress, errs := util.Get(urlStr)
		if errs != nil {
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}
		resss := ress.(map[string]interface{})["songs"].([]interface{})[0].(map[string]interface{})
		out["id"] = resss["id"]
		out["album"] = resss["al"].(map[string]interface{})["name"]
		out["name"] = resss["name"].(string)
		out["singer"] = resss["ar"].([]interface{})[0].(map[string]interface{})["name"].(string)
		out["picUrl"] = resss["al"].(map[string]interface{})["picUrl"]
		out["platform"] = "wyy"
		out["url"] = bodyMapData["url"]
		out["size"] = bodyMapData["size"]
		out["br"] = bodyMapData["br"]

		//获取歌词
		urlStr = "https://music.163.com/api/song/lyric?lv=-1&kv=-1&tv=-1&id=" + service.Ids
		b, errs := util.Get(urlStr)
		if errs != nil {
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}
		if strconv.FormatFloat(b.(map[string]interface{})["code"].(float64), 'f', -1, 64) == "200" {
			out["lyric"] = b.(map[string]interface{})["lrc"].(map[string]interface{})["lyric"]
		} else {
			out["lyric"] = "failed"
		}
		return serializer.OkResponse(out)
	} else if service.Platform == "qq" {
		//获取歌曲的详细信息
		out := map[string]interface{}{}

		url := "https://c.y.qq.com/v8/fcg-bin/fcg_play_single_song.fcg?format=json&songmid=" + service.Ids

		resss, errs := util.QQGet(url)
		if errs != nil {
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}
		ressss := resss.(map[string]interface{})["data"].([]interface{})[0].(map[string]interface{})
		out["id"] = ressss["mid"]
		out["album"] = ressss["album"].(map[string]interface{})["name"]
		out["name"] = ressss["name"].(string)
		out["singer"] = ressss["singer"].([]interface{})[0].(map[string]interface{})["name"].(string)
		out["picUrl"] = "https://y.qq.com/music/photo_new/T002R300x300M000" + ressss["album"].(map[string]interface{})["mid"].(string) + ".jpg"
		out["platform"] = "qq"
		// out["url"] = kw.UsingKwSong(out["name"].(string), out["singer"].(string), "3")
		out["url"] = migu.UsingMiguSong(out["name"].(string), out["singer"].(string), "3")

		//获取歌词
		url = "https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?format=json&nobase64=1&g_tk=5381&songmid=" + service.Ids
		b, errs := util.QQGet(url)
		if errs != nil {
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}
		if strconv.FormatFloat(b.(map[string]interface{})["code"].(float64), 'f', -1, 64) == "0" {
			out["lyric"] = b.(map[string]interface{})["lyric"]
		} else {
			out["lyric"] = "failed"
		}
		return serializer.OkResponse(out)

	} else if service.Platform == "kw" {
		url := "https://antiserver.kuwo.cn/anti.s?type=convert_url3&format=mp3&response=url&rid=" + service.Ids + "&br=1000kape"

		res, err := util.Get(url)
		if err != nil {
			return err
		}

		out := map[string]interface{}{}

		if strconv.FormatFloat(res.(map[string]interface{})["code"].(float64), 'f', -1, 64) == "200" {
			newUrl := res.(map[string]interface{})["url"].(string)
			out["url"] = newUrl
		} else {
			out["url"] = "failed"
		}

		//获取歌曲详细信息
		url = "http://m.kuwo.cn/newh5/singles/songinfoandlrc?musicId=" + service.Ids + "&httpsStatus=1"

		ress, err := util.KuwoGet(url)
		if err != nil {
			return err
		}
		resss := ress.(map[string]interface{})["data"].(map[string]interface{})["songinfo"].(map[string]interface{})
		out["id"] = resss["id"]
		out["album"] = resss["album"]
		out["name"] = resss["songName"]
		out["singer"] = resss["artist"]
		picUrl := resss["pic"].(string)
		out["picUrl"] = strings.Replace(picUrl, "/240/", "/500/", -1)
		out["platform"] = "kw"

		//获取歌词
		ressss := ress.(map[string]interface{})["data"].(map[string]interface{})["lrclist"]
		if ressss == nil {
			out["lyric"] = "[00:00:00]暂无歌词 "
		} else {
			var lyric string
			for _, v := range ressss.([]interface{}) {
				time := v.(map[string]interface{})["time"].(string)
				content := v.(map[string]interface{})["lineLyric"].(string)
				//取ms,即.后面的数字
				comma := strings.Index(time, ".")
				ms := time[comma+1:]

				newTime, _ := strconv.Atoi(time[:comma])
				m := newTime / 60

				s := newTime % 60

				//golang不支持三元表达式，所有用If判断
				var newM string
				var newS string
				if m < 10 {
					newM = "0" + strconv.Itoa(m)
				} else {
					newM = strconv.Itoa(m)
				}
				if s < 10 {
					newS = "0" + strconv.Itoa(s)
				} else {
					newS = strconv.Itoa(s)
				}
				timeString := newM + ":" + newS + ":" + ms
				lyric = lyric + "[" + timeString + "]" + content + "\n"
			}
			out["lyric"] = lyric
		}
		return serializer.OkResponse(out)

	} else if service.Platform == "kg" {
		url := "https://wwwapi.kugou.com/yy/index.php?r=play/getdata&hash=" + service.Hash + "&album_id=" + service.Ids

		res, err := util.KugouGet(url)
		if err != nil {
			return err
		}

		out := map[string]interface{}{}

		ress := res.(map[string]interface{})["data"].(map[string]interface{})
		out["id"] = ress["album_id"]
		out["hash"] = ress["hash"]
		out["album"] = ress["album_name"]
		out["name"] = ress["song_name"]
		out["singer"] = ress["author_name"]
		out["picUrl"] = ress["img"]
		out["platform"] = "kg"
		out["lyric"] = ress["lyrics"]

		// out["url"] = kw.UsingKwSong(out["name"].(string), out["singer"].(string), "3")
		out["url"] = migu.UsingMiguSong(out["name"].(string), out["singer"].(string), "3")

		return serializer.OkResponse(out)
	}
	return nil
}
